'use strict';

/* Magic Mirror
 * Module: MMM-PIR-Sensor
 *
 * By Paul-Vincent Roll http://paulvincentroll.com
 * MIT Licensed.
 */

const NodeHelper = require('node_helper');
var exec = require('child_process');
var CronJob = require("cron").CronJob;

module.exports = NodeHelper.create({

  // Subclass socketNotificationReceived received.
  socketNotificationReceived: function(notification, payload) {
	  console.log("MMM-Sensor helper:receive:"+notification)
    if (notification === 'CONFIG') {
		this.config=payload;
		console.log("powerOnCron: "+this.config.powerOnCron);
		console.log("powerOffCron: "+this.config.powerOffCron);
		
		exec.exec("sudo "+__dirname+"/on_off " + this.config.sensorPIN+" "+this.config.powerOnState, (error, stdout) => {
		   if (error) {
				console.log("exec error: "+error);
				return;
			  }
			  console.log("stdout: " +stdout);
			  this.sendSocketNotification('POWER_ON', null);
		});
		
		var self=this;
		this.config.onCron=new CronJob(this.config.powerOnCron, function () {  
			//your job code here  
			exec.exec("sudo "+__dirname+"/on_off " + self.config.sensorPIN+" "+self.config.powerOnState, (error, stdout) => {
			   if (error) {
					console.log("exec error: "+error);
					return;
				  }
				  console.log("stdout: " +stdout);
				  self.sendSocketNotification('POWER_ON', null);
			});
		}, null, true, 'Asia/Shanghai'); 
		this.config.offCron=new CronJob(this.config.powerOffCron, function () {
			//your job code here  
			exec.exec("sudo "+__dirname+"/on_off " + self.config.sensorPIN+" "+self.config.powerOffState, (error, stdout) => {
			   if (error) {
					console.log("exec error: "+error);
					return;
				  }
				  console.log("stdout: " +stdout);
				  self.sendSocketNotification('POWER_OFF', null);
			});
		}, null, true, 'Asia/Shanghai'); 
	}
  }

});
